package com.hongdee.crm.task.service.impl;

import com.hongdee.annotation.MethodComment;
import com.hongdee.common.util.DateUtils;
import com.hongdee.common.util.StringUtil;
import com.hongdee.crm.Constant;
import com.hongdee.crm.task.dao.IBcMaintainTypeTaskDao;
import com.hongdee.crm.task.dao.ITCrmCarMaintainTaskDao;
import com.hongdee.crm.task.dao.ITCrmTaskDao;
import com.hongdee.crm.task.dto.MainTainDTO;
import com.hongdee.crm.task.entity.TCrmTask;
import com.hongdee.crm.task.service.ITCrmCarMaintainTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by My on 2017/4/27.
 */
@Service("FirstMonthMaintainTaskService")
public class TCrmCarFirstMonthMaintainTaskServiceImpl implements ITCrmCarMaintainTaskService {

    private final String YYYYMMDD="yyyy-MM-dd";
    private final int LIMIT = 1000;
    private final String MAINTAINNAME="首月";

    private final String BY_CODE="by";
    private final String SY="sy";
    private final String TXTS="txts";
    private final String MBR="mbr";

    private MainTainDTO mbrMainTainDTO;

    @Autowired
    private ITCrmCarMaintainTaskDao carMaintainTaskDao;
    @Autowired
    private ITCrmTaskDao taskDao;
    @Autowired
    private IBcMaintainTypeTaskDao bcMaintainTypeTaskDao;


    @Override
    @MethodComment(name = "新车首月提醒任务")
    public Integer carMaintainQuartz() throws Exception {
        Integer nums=0;
        List<Map<String,Object>> companyList=carMaintainTaskDao.findCompanyList(SY+"_"+MBR,SY+"_"+MBR);
        //遍历公司信息
        for(Map<String,Object> map:companyList){
            //取得公司ID
            String compnayId=String.valueOf(map.get("company_id"));
            //根据公司ID 判断是否有首保任务 首保月任务
            int num=this.carMaintain(compnayId,"","");
            nums+=num;
        }
        return nums;
    }

    @Override
    public Integer carMaintain(String companyId, String startTime, String endTime) throws Exception {
        long nowTime=MaintainUtil.getNowTime();
        this.getMainTainParamInfo(companyId);
        long maintainTime= DateUtils.addMonthLongTime(nowTime,-1);
        return findCarFirstMonthMaintain(maintainTime, companyId,nowTime,startTime,endTime);
    }

    private Integer findCarFirstMonthMaintain(long maintainTime,String companyId,long nowTime,String startTime,String endTime) throws Exception {
        Integer nums=0;
        int start = 0;
        List<Map<String,Object>> maintainTypeList=bcMaintainTypeTaskDao.findSetMaintainType(companyId,SY);
        if(maintainTypeList!=null) {
            while (true) {
                //生成sql相关
                List<Map<String,Object>> carList=this.findCarList(maintainTime,companyId,start*LIMIT,LIMIT);
                if(carList.size()==0){
                    start=0;
                    break;
                }
                List<TCrmTask> tCrmTaskList=this.analyCarList(carList,startTime,endTime,companyId);
                //解析车辆信息
                if(tCrmTaskList.size()>0){
                    int num=tCrmTaskList.size();
                    carMaintainTaskDao.insertMaintailLists(tCrmTaskList);
                    nums+=num;
                }
                start++;
            }
        }
        return nums;
    }

    private List<TCrmTask> analyCarList(List<Map<String,Object>> carList,String startTime,String endTime,String companyId) throws Exception {
        int nMonth = Integer.valueOf(DateUtils.getTimeStr("MM"));
        List<TCrmTask> taskList=new ArrayList<>();
        for (Map<String,Object> carMap:carList) {
            //改为取销售日期 2017-05-09
            if(carMap.get("buyDate")==null){
                continue;
            }
            //车辆质保时间
//            Long guaranteeDate=Long.valueOf(String.valueOf(carMap.get("guaranteeStartDate")));
            //改为取销售日期 2017-05-09
            Long guaranteeDate=Long.valueOf(String.valueOf(carMap.get("buyDate")));
            Long nextMonth= DateUtils.addMonthLongTime(guaranteeDate,+1);
            //提醒天数
            Long expectDate=DateUtils.addDayLongTime(nextMonth,-mbrMainTainDTO.getTxtsNums().intValue());
            int m = Integer.valueOf(DateUtils.getTimeStr(new Date(expectDate),"MM"));
            boolean timeFlag=false;
            if(nMonth==m){
                timeFlag=true;
            }else{
                timeFlag=false;
            }
            timeFlag=DateUtils.checkTime(expectDate,startTime,endTime);
            if(timeFlag){
                //可以进行保存
                TCrmTask tCrmTask=this.createTcrmTask(carMap,expectDate,companyId,nextMonth,guaranteeDate);
                if(tCrmTask!=null){
                    taskList.add(tCrmTask);
                }
            }
        }
        return taskList;
    }

    private boolean checkSYTask(String companyId,String carId,String code,long expectDate) throws Exception {
        String expectDateStr=DateUtils.formatLongTime(expectDate,YYYYMMDD);
        List<Map<String,Object>> lists=taskDao.findTasks(companyId,carId,BY_CODE,code,expectDateStr);
        if(lists!=null){
            if(lists.size()>0){
                return true;
            }
        }
        return false;
    }

    private TCrmTask createTcrmTask(Map<String,Object> carMap,Long expectDate,String companyId,Long nextMonth,Long guaranteeDate) throws Exception {
        if(mbrMainTainDTO.getTxtsNums()!=null) {
            String expectDateStr = DateUtils.getTimeStr(new Date(expectDate), "yyyy-MM-dd");
            String guaranteeDateStr = DateUtils.getTimeStr(new Date(guaranteeDate), "yyyy-MM-dd");
            boolean flag = taskDao.checkTaskByVinAndId(companyId, StringUtil.formatEmpty(carMap.get("vin")),StringUtil.formatEmpty(carMap.get("id")), mbrMainTainDTO.getCode(), BY_CODE, expectDateStr);
            if (flag) {
                return null;
            }
            String plateNum = "";
            if (carMap.get("plateNum") == null) {
                String vin = String.valueOf(carMap.get("vin"));
                plateNum = vin.substring(vin.length() - 6, vin.length());
            } else {
                plateNum = String.valueOf(carMap.get("plateNum"));
            }
            TCrmTask task = new TCrmTask();
            task.setCompanyId(companyId);
            task.setCreateTime(new Date().getTime());
            task.setVIN(StringUtil.formatNull(carMap.get("vin")));
            task.setCarId(StringUtil.formatNull(carMap.get("id")));
            task.setPlateNum(plateNum);
            task.setLinkman(StringUtil.formatNull(carMap.get("ownerName")));
            task.setLinkphone(StringUtil.formatNull(carMap.get("contactTel")));
            task.setExpectDate(expectDateStr);
            task.setStatus("0");
            task.setIsBack("0");
            task.setTypePCode(BY_CODE);
            task.setTypeCode(SY + "_" + MBR);
            task.setContent(String.format("%s的车,车主[%s]，%s首月提醒，销售日期%s", plateNum, task.getLinkman(),
                    DateUtils.getTimeStr(new Date(nextMonth), "yyyy-MM-dd"), guaranteeDateStr));
            return task;
        }else{
            return null;
        }
    }

    /**
     * 查询出质保时间一个月内的车辆数据
     * @param maintainTime
     * @param companyId
     * @return
     * @throws Exception
     */
    private List<Map<String, Object>> findCarList(long maintainTime, String companyId,int start,int limit) throws Exception {
        StringBuffer sql=new StringBuffer();
        sql.append(" select * from t_crm_car car where " +
//                "car.guarantee_start_date>=? " +
                " car.buy_date >=? and car.buy_date is not null "+
                " and car.company_id=?  " +
                " and car.from_company='是' " +
                " and NOT EXISTS( " +
                " select * from t_crm_car_workorder where car.vin=vin and car.company_id=company_id and wx_type in ('首保','二保','定保')" +
                " ) ");
        Constant.REMIND_CLOSE_SQL(sql,SY,mbrMainTainDTO.getCode(),"car");
        sql.append("limit ?,? ");
        System.out.println(sql);
        return this.taskDao.list(sql.toString(),maintainTime,companyId,start,limit);
    }

    private void getMainTainParamInfo(String companyId)throws Exception{

        List<Map<String,Object>> mbrList=carMaintainTaskDao.findCompanyParamList(companyId,SY+"_"+MBR);
        if(mbrList!=null) {
            mbrMainTainDTO = MainTainDTO.analyParams(mbrList, SY + "_" + MBR + "_" + TXTS, null, SY + "_" + MBR);
            mbrMainTainDTO.setCode(SY + "_" + MBR);
            this.setMbrMainTainDTO(mbrMainTainDTO);
        }
    }

    public MainTainDTO getMbrMainTainDTO() {
        return mbrMainTainDTO;
    }

    public void setMbrMainTainDTO(MainTainDTO mbrMainTainDTO) {
        this.mbrMainTainDTO = mbrMainTainDTO;
    }
}
